﻿package bdz.extensions.youtube.json {
	import bdz.common.events.GenericEvent;
	import bdz.common.events.XMLLoaderEvent;
	import bdz.extensions.youtube.events.YTEvent;
	import bdz.extensions.youtube.json.vo.YTJSONFeedEntry;
	import flash.events.EventDispatcher;
	import bdz.common.model.XMLLoader;
	import com.adobe.serialization.json.*;
	
	/**
	 * ...
	 * @author Donald
	 */
	public class YTJSONFeed extends EventDispatcher {
		private var endpoint:String = "http://gdata.youtube.com/feeds/"
		private var gdata:Object;
		function YTJSONFeed(act:String, type:String = "uploads", isapi:Boolean = false) {
			if (isapi) {
				endpoint = "http://gdata.youtube.com/feeds/api/"
			}
			if(act){
				endpoint += "users/" + act + "/";
			}
			if (type) {
				endpoint += type;
			}
			endpoint += "?alt=json&format=5";
			
			
		}
		private function onFeedReceived(evt:XMLLoaderEvent):void {
			var res:String = evt.data;
			
			var results:Object = JSON.decode(res);
			var listing:Array = new Array();
			var counter:Number = 0;
			trace(results.feed.entry);
			for each(var obj:Object in results.feed.entry) {
				var fe:YTJSONFeedEntry = new YTJSONFeedEntry(obj);
				listing.push(fe);
				counter++;
			}
			listing.sortOn("microTime", Array.NUMERIC | Array.DESCENDING);
			dispatchEvent(new YTEvent(YTEvent.COMPLETE, listing));
		}
		public function retrieveFeed(params:Object = null):void {
			if(params){
				for (var prop in params) {
					if(params[prop]){
						var str:String = "&" + prop + "=" + params[prop];
						endpoint += str;
					}
				}
			}
			var loader:XMLLoader = new XMLLoader("onFeedReceived");
			loader.addEventListener("onFeedReceived", onFeedReceived);
			loader.location = endpoint;
			trace(">>>> " + endpoint);
			loader.send();
		}
		
	}
	
}